package smtp

import (
	"io"

	"gitee.com/Luna-CY/Golang-Project-Template/internal/configuration"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/context"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/errors"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/logger"
	"gitee.com/Luna-CY/Golang-Project-Template/internal/service/system_smtp_service/provider"
	"gitee.com/Luna-CY/Golang-Project-Template/model"
	"gopkg.in/gomail.v2"
)

func New(config configuration.SmtpProvider) (*Smtp, errors.Error) {
	return &Smtp{config: config}, nil
}

type Smtp struct {
	config configuration.SmtpProvider
}

func (cls *Smtp) GetName() string {
	return cls.config.Name
}

func (cls *Smtp) GetFrom() string {
	return cls.config.Smtp.From
}

func (cls *Smtp) Send(ctx context.Context, from string, to []string, cc []string, bcc []string, subject string, bodyType model.SystemSmtpLogBodyType, body string, attachments []provider.Attachment) errors.Error {
	var dialer = gomail.NewDialer(cls.config.Smtp.Host, cls.config.Smtp.Port, cls.config.Smtp.User, cls.config.Smtp.Pass)

	var message = gomail.NewMessage()

	message.SetHeader("From", from)
	message.SetHeader("To", to...)

	for _, c := range cc {
		message.SetAddressHeader("Cc", c, "")
	}
	for _, b := range bcc {
		message.SetAddressHeader("Bcc", b, "")
	}

	var bt = "text/plain"
	if bodyType == model.SystemSmtpLogBodyTypeHtml {
		bt = "text/html"
	}

	message.SetHeader("Subject", subject)
	message.SetBody(bt, body)

	for _, attachment := range attachments {
		message.Attach(attachment.Filename, gomail.SetCopyFunc(func(w io.Writer) error {
			_, err := io.Copy(w, attachment.Reader)
			return err
		}))
	}

	if err := dialer.DialAndSend(message); err != nil {
		logger.SugarLogger(logger.WithRequestId(ctx), logger.WithStack()).Errorf("ISSPS_TP.S_TP.S_ND.430800 send email failed: %v", err)

		return errors.ErrorServerInternalError("ISSPS_TP.S_TP.S_ND.450812", "发送邮件失败")
	}

	return nil
}
